package cn.abcode.test.springbootsecurity.demo.filter;

import com.mysql.cj.util.StringUtils;
import org.springframework.http.HttpRequest;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 *
 * 验证码校验
 */
@Component
public class VerifyCodeFilter extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

       String method = request.getMethod().toLowerCase();
       String servletPath = request.getServletPath();
       if("post".equals(method) && "/doLogin".equals(servletPath)){
           String requestCode = request.getParameter("verifyCode");
           String sessionCode = (String) request.getSession().getAttribute("verify_code");
           if(StringUtils.isNullOrEmpty(requestCode)){
               throw new AuthenticationServiceException("验码不能为空");
           }
           if(!requestCode.equals(sessionCode)){
               throw new AuthenticationServiceException("验证码错误");
           }
       }

       filterChain.doFilter(request, response);
    }
}
